// pages/battle/battle.js
let timer = null
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},               // 用户信息
    questions: [],              // 题目
    questionNow: {},            // 当前是哪一题目
    indexNow: 1,                // 当前第几题
    rightAnswer: 0,             // 当前的正确答案
    chooseOne: {},              // 选项1
    chooseTwo: {},              // 选项2
    chooseThree: {},            // 选项3
    chooseFour: {},             // 选项4
    chooseBtn1: '',             // 选项1样式
    chooseBtn2: '',             // 选项2样式
    chooseBtn3: '',             // 选项3样式
    chooseBtn4: '',             // 选项4样式
    scoreBar: 0,                // 用户总得分
    thisScore: 0,               // 用户答对题数
    answerIndex: 0,             // 用户选择第几题
    userFinish: false,          // 用户完成答题
    myScore: '0',               // 用户分数百分比
    oponInfo: {},               // 对手个人信息
    opponentsScore: 0,          // 对手总得分
    opponentsAnswer: 0,         // 对手选择的答案
    opponentFinish: false,      // 对手完成答题
    hisScore: '0',              // 对手分数百分比
    userAnswers: [],            // 用户答题记录
    robotAnswers: [],           // 机器人答题记录
    titleAnimationData: {},
    typeAnimationData: {},
    questionAnimation: {},
    chooseAnimation: {},
    count: 10,
    imgSrc: '@2x',
    hideVs: 1,
    battle_id: '',
    isRobot: false,
    questionTitle: ['第一题', '第二题', '第三题', '第四题', '最后一题'],
    questionTurnNone: 'animated fadeIn',
    questionNone: 'displayNone',
    userALeft: '-240',
    userBRight: '-240',
    opponentOut: false            // 对手是否退出
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 拿到的对手信息
    this.setData({
      imgSrc: app.globalData.imgSrc,
      oponInfo: app.globalData.onlineBattleInfo.opponentInfo || app.globalData.onlineBattleInfo,
      userInfo: app.globalData.userInfo,
      battle_id: app.globalData.onlineBattleInfo.battle_id || app.globalData.battleId
    })
    setTimeout(() => {
      this.setData({
        userALeft: '150',
        userBRight: '60'
      })
    }, 500)
    if (app.globalData.onlineBattleInfo.isRobot) {
      this.setData({
        isRobot: app.globalData.onlineBattleInfo.isRobot
      })
    }
    // 
    // 开启ws连接
    wx.connectSocket({
      url: 'wss://tydr.tihe-china.com/wss'
      // url: 'ws://120.27.224.239:8888'
    })
    // 监听ws的服务器返回
    wx.onSocketMessage((res) => {
      const resData = JSON.parse(res.data)
      // 拿到对手的每一题的答题情况
      if (resData.command === 'answer') {
        const { opponentsScore } = this.data
        this.setData({
          opponentsScore: opponentsScore + resData.singleAnswer.score,
          opponentsAnswer: resData.singleAnswer.answerIndex,
          opponentFinish: true,
          hisScore: parseInt((opponentsScore + resData.singleAnswer.score) / 9)
        })
        this.finishAnswer()
      } else if (resData.command === 'questions') {
        this.setData({
          questions: resData.questions
        })
        setTimeout(() => {
          if (!this.data.opponentOut) {
            this.setData({
              hideVs: 2
            }, () => {
              setTimeout(() => {
                this.judgeQuestions();
              }, 50)
            });
          }
        }, 2200)
      } else if (resData.command === 'opponent_offline') {
        this.quert()
      }
    })
    // 服务开启
    wx.onSocketOpen((res) => {
      let battleId = this.data.battle_id
      let dataString = JSON.stringify({
        command: "battle_start",
        wx_id: app.globalData.wx_id,
        battle_id: battleId
      })
      wx.sendSocketMessage({
        data: dataString
      })
    })
    // 服务异常
    wx.onSocketError(function (res) {
      // console.log('WebSocket连接打开失败，请检查！')
      wx.showToast({
        title: '服务异常',
        icon: 'none',
        complete: () => {
          setTimeout(() => {
            wx.redirectTo({
              url: '../index/index'
            })
          }, 1500)
        }
      })
    })
    wx.onSocketClose
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // const { userInfo } = app.globalData
    // const { self, index } = this.data
   
    // this.setData({
    //   self: {
    //     ...self,
    //     userInfo,
    //   },
    //   type: '娱乐',
    //   title: `第${titleMap[`${index}`]}题`,
      
    // }, () => {
    //   // console.warn(userInfo,this.data.self)
    // })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(timer)
    wx.closeSocket()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(timer)
    wx.closeSocket()
    // this.countdownTimer = null
    // clearInterval(
    //   this.countdownTimer
    // )
  },
  quert: function () {
    this.setData({
      opponentsScore: 0
    })
    this.setData({
      opponentOut: true,
      hideVs: 3
    })
    clearInterval(timer)
    let dataString = ''
    let battleId = this.data.battle_id
    if (this.data.isRobot) {
      dataString = JSON.stringify({
        command: "battle_end",
        wx_id: app.globalData.wx_id,
        battle_id: battleId,
        userAnswers: this.data.userAnswers,
        robotAnswers: this.data.robotAnswers
      })
    } else {
      dataString = JSON.stringify({
        command: "battle_end",
        wx_id: app.globalData.wx_id,
        battle_id: battleId,
        userAnswers: this.data.userAnswers
      })
    }
    wx.sendSocketMessage({
      data: dataString
    })
    app.globalData.userInfo.score += this.data.scoreBar
  },
  // 把当前第几题展示在页面中
  judgeQuestions: function () {
    const { questions,indexNow } = this.data;
    const question = questions[indexNow - 1];
    this.setData({
      questionNow: question,  // 当前是哪一题
      rightAnswer: question.rightAnswer,
      chooseBtn1: '',           // 选项1样式
      chooseBtn2: '',           // 选项2样式
      chooseBtn3: '',           // 选项3样式
      chooseBtn4: '',            // 选项4样式
      opponentFinish: false,
      userFinish: false,
      opponentsAnswer: 0,
      questionTurnNone: 'animated fadeIn',
      questionNone: 'displayNone',
      answerIndex: 0,
      chooseOne: {
        index: 1,
        value: question.answer1
      },             // 选项1
      chooseTwo: {
        index: 2,
        value: question.answer2
      },              // 选项2
      chooseThree: {
        index: 3,
        value: question.answer3
      },            // 选项3
      chooseFour: {
        index: 4,
        value: question.answer4
      },             // 选项4
    });

    setTimeout(() => {
      this.setData({
        questionTurnNone: 'animated fadeOut'
      })
    }, 1000)
    setTimeout(() => {
      this.setData({
        questionNone: 'displayBlock'
      })
      this.countTime()
    }, 2000)
  },
  // 倒计时
  countTime: function () {
    const { indexNow, battle_id, answerIndex } = this.data
    this.setData({
      count: 10
    })
    if (timer) {
      clearInterval(timer)
    }
    let timeCunt = 10
    //  如果是机器人
    if (this.data.isRobot) {
      const { opponentsScore, rightAnswer } = this.data
      const robotTime = Math.floor(Math.random() * 9001 + 1000)
      const opponentsAnswer = Math.floor(Math.random() * 3 + 1)
      setTimeout(() => {
        let robotScore = 0
        let count = this.data.count
        if (opponentsAnswer === rightAnswer) {
          if (count >= 8) {
            robotScore = 180
          } else if (count < 8 && count >= 5) {
            robotScore = 160
          } else if (count < 5 && count > 0) {
            robotScore = 80
          } else {
            robotScore = 0
          }
        }
        let barPre = parseInt((opponentsScore + robotScore) / 9)
        this.setData({
          opponentsScore: opponentsScore + robotScore,
          opponentsAnswer: opponentsAnswer,
          opponentFinish: true,
          hisScore: barPre
        })
        this.finishAnswer()
      }, robotTime)
    }
    timer = setInterval(() => {
      timeCunt--
      this.setData({
        count: timeCunt
      })
      if (timeCunt === 0) {
        clearInterval(timer)
        if (this.data.isRobot) {
          this.setData({
            userFinish: true
          })
        }
        // 超过10S关闭定时器，发送0分给ws
        if (!this.data.isRobot && !this.data.userFinish) {
          this.setData({
            userFinish: true
          })
          const singleAnswer = {
            command: 'answer',
            wx_id: app.globalData.wx_id,
            battle_id: battle_id,
            singleAnswer: {
              questionIndex: indexNow,    //当前答题的序号，1-5
              answerIndex: 0,             //当前题目用户所回答的选项序号
              score: 0                    //当前题目用户得分
            }
          }
          // 如果对手不是机器人，发信息
          this.sendAnswer(singleAnswer)
        }
        this.finishAnswer()
        if (!this.data.opponentFinish) {
          setTimeout(() => {
            if (!this.data.opponentFinish) {
              this.quert()
            }
          }, 2000)
        }
      }
      // if (timeCunt < 0) {
      //   this.quert()
      // }
    }, 1000)
  },
  // 用户选择了答案
  chooseAnswer: function (event) {
    // console.log(event.currentTarget.dataset.curindex)
    const chooseIndex = event.currentTarget.dataset.curindex
    const { questionNow, count, scoreBar, indexNow, rightAnswer, userFinish, thisScore, battle_id, answerIndex } = this.data
    if (userFinish) return false
    let answerScore = 0
    let rightScore = thisScore
    if (chooseIndex === rightAnswer) {
      rightScore++
      if (count >= 8) {
        answerScore = 180
      } else if (count < 8 && count >= 5) {
        answerScore = 160
      } else if (count < 5 && count > 0) {
        answerScore = 80
      } else {
        answerScore = 0
      }
      this.setData({
        ['chooseBtn' + chooseIndex]: 'rightAnswer'
      })
    } else {
      answerScore = 0
      this.setData({
        ['chooseBtn' + chooseIndex]: 'wrongAnswer'
      })
    }
    let scoreNow = scoreBar + answerScore
    let barPre = parseInt(scoreNow / 9)
    this.setData({
      scoreBar: scoreNow,
      answerIndex: chooseIndex,       // 选择的答案
      userFinish: true,
      myScore: barPre,
      thisScore: rightScore
    })
    if (!this.data.isRobot) {
      // 如果对手不是机器人，发信息
      const singleAnswer = {
        command: 'answer',
        wx_id: app.globalData.wx_id,
        battle_id: battle_id,
        singleAnswer: {
          questionIndex: indexNow,    //当前答题的序号，1-5
          answerIndex: chooseIndex,   //当前题目用户所回答的选项序号
          score: answerScore          //当前题目用户得分
        }
      }
      this.sendAnswer(singleAnswer)
    }
    this.finishAnswer()
  },
  finishAnswer: function () {
    if (this.data.userFinish && this.data.opponentFinish) {
      // 用户和对手都完成了答题
      const { questionNow, indexNow, opponentsAnswer, rightAnswer, answerIndex, userAnswers, robotAnswers } = this.data
      let userAnserInfo = {
        type: questionNow.type,
        isRight: answerIndex === rightAnswer
      }
      let robotAnserInfo = {
        type: questionNow.type,
        isRight: opponentsAnswer === rightAnswer
      }
      userAnswers.push(userAnserInfo)
      robotAnswers.push(robotAnserInfo)
      this.setData({
        userAnswers: userAnswers,
        robotAnswers: robotAnswers
      })
      clearInterval(timer)
      if (opponentsAnswer === rightAnswer) {
        this.setData({
          ['chooseBtn' + opponentsAnswer]: 'rightAnswer'
        })
      } else {
        if (opponentsAnswer !== 0) {
          this.setData({
            ['chooseBtn' + opponentsAnswer]: 'wrongAnswer'
          })
        }
      }
      setTimeout(() => {
        this.setData({
          ['chooseBtn' + rightAnswer]: 'rightAnswer'
        })
      }, 1500)
      if (indexNow < 5) {
        let index = indexNow + 1
        this.setData({
          indexNow: index
        })
        setTimeout(() => {
          this.judgeQuestions()
        }, 2500)
      } else {
        setTimeout(() => {
          this.setData({
            hideVs: 3
          })
        }, 3000)
        let dataString = ''
        let battleId = this.data.battle_id
        if (this.data.isRobot) {
          dataString = JSON.stringify({
            command: "battle_end",
            wx_id: app.globalData.wx_id,
            battle_id: battleId,
            userAnswers: this.data.userAnswers,
            robotAnswers: this.data.robotAnswers
          })
        } else {
          dataString = JSON.stringify({
            command: "battle_end",
            wx_id: app.globalData.wx_id,
            battle_id: battleId,
            userAnswers: this.data.userAnswers
          })  
        }
        wx.sendSocketMessage({
          data: dataString
        })
      }
    }
  },
  // 对手不是机器人，每答一题发送的请求
  sendAnswer: function (singleAnswer) {
    wx.sendSocketMessage({
      data: JSON.stringify(singleAnswer)
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '太影达人',
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})